from django import forms
from django.conf import settings
from django.template.context import Context
from django.template.loader import get_template
from django.utils.safestring import mark_safe
from django.forms.widgets import flatatt
from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.html import conditional_escape
from django.utils.html import escape
from django.forms.util import smart_unicode
        
class AjaxInput(forms.TextInput ):
    template = None
    input_type ="text"
    
    def __init__(self, attrs={}):
        attrs['autocomplete'] = "off"
        super(AjaxInput, self).__init__(attrs)    
    
    def _get_context(self, name, value=None, attrs=None):
        if value is None: value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = escape(smart_unicode(value))

        return {'id' :  attrs.get('id'),                
                'attrs': final_attrs,
                'flatattrs' : u''.join([u' %s=%s' % (k, conditional_escape(v)) for k, v in final_attrs.items()]),
                }    
    
    def render(self, name, value=None, attrs=None):
        p = self._get_context(name, value, attrs)
        t = get_template(self.template)        
        return  t.render(Context(p)) 
            
    class Media:
        js = (
               settings.XADMIN_MEDIA_URL + "js/jquery/jquery-1.3.2.min.js",
              )
        
class DatePickerWidget(AjaxInput, forms.TextInput):
    """
         jquery-ui widget for date formatting
         
         options      
             format   : date format
                         @see http://docs.jquery.com/UI/Datepicker/formatDate
             duration: Control the speed at which the datepicker appears. 
                         Time in milliseconds or '' for immediately. 
             template : template used by render method ['xadmin/widgets/date_picker.html']
             
    """
    input_type = 'text'
    template = 'xadmin/widgets/date_picker.html'
    format = 'yy-mm-dd'
    duration = ''
    
    class Media(AjaxInput.Media):
        js = (
              settings.XADMIN_MEDIA_URL + "js/jquery/jquery-ui.1.7.2.min.js",
              )
        css = {
            'all': (settings.XADMIN_MEDIA_URL + "css/jquery.autocomplete.css",)
        }
            
    def __init__(self, attrs={}):
        attrs['size'] = 10
        super(DatePickerWidget, self).__init__(attrs)
    
    def _get_context(self, name, value=None, attrs=None):
        p = super(DatePickerWidget, self)._get_context(name, value, attrs)
        p.update( {'format': self.format, 'duration':self.duration } )
        return p

from xadmin.ajax.widgets.autocomplete import AjaxLookupInput
